package com.loren.demo23.controller;

import com.loren.demo23.license.License;
import com.loren.demo23.license.LicenseService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@RestController
@RequiredArgsConstructor
@RequestMapping("/license")
public class LicenseController {

    private final LicenseService licenseService;

    @GetMapping("/download")
    public void downloadLicense(HttpServletResponse response) throws IOException {
        License license = getLicense();
        String licenseText = this.licenseService.licenseText(license);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=license");
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.write(licenseText, outputStream, StandardCharsets.UTF_8);
    }

    @GetMapping("/validate")
    public String validate() throws IOException {
        String licenseText = StreamUtils.copyToString(new ClassPathResource("license").getInputStream(), StandardCharsets.UTF_8);
        this.licenseService.validate(licenseText);
        return "success";
    }

    private License getLicense() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.now();
        License license = new License();
        license.setCompany("Alibaba");
        license.setHardwareUUID("4C4C4544-0030-4410-8056-B8C04F434A33");
        license.setUserCount(100L);
        license.setStartTime(formatter.format(localDate));
        license.setExpireTime(formatter.format(localDate.plusYears(5)));
        return license;
    }
}
